//
//  SelectViewController.swift
//  CTCollectionViewDemo
//
//  Created by GodCoder on 2019/8/9.
//  Copyright © 2019 CTCollectionView. All rights reserved.
//

import UIKit
import Photos

class SelectViewController: UIViewController {

    @IBOutlet weak var downView: UIView!
    @IBOutlet weak var topView: UIView!
    
    let cellSize = CGSize(width: 80, height: 80)
    lazy var collectionView: UICollectionView = {
        
        let layout = SelectFlowLayout.init()
        layout.itemSize = cellSize
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        let cv = UICollectionView.init(frame : topView.frame, collectionViewLayout : layout)
        cv.delegate  = self
        cv.dataSource = self
        cv.allowsMultipleSelection = true
        cv.backgroundColor = .white
        cv.register(UINib.init(nibName: "SelectCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "SelectCollectionViewCellID")
        return cv
    }()
    lazy var collectionView2: UICollectionView = {
        let layout = SelectFlowLayout.init()
        layout.itemSize = cellSize
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        layout.scrollDirection = .horizontal
        let cv = UICollectionView.init(frame : downView.frame, collectionViewLayout : layout)
        cv.delegate  = self
        cv.dataSource = self
        cv.backgroundColor = .white
        cv.register(UINib.init(nibName: "SelectCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "SelectCollectionViewCellID2")
        return cv
    }()
    
    lazy var photosArray : PHFetchResult<PHAsset> = {
        let allOptions = PHFetchOptions()
        // 按照时间排序
        /// 这里设置的key = 'creationDate' 排序字段可以按照已有的属性去查 ascending:升序和降序属性
        /*
         open class func fetchAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         open class func fetchAssets(withLocalIdentifiers identifiers: [String], options: PHFetchOptions?) -> PHFetchResult<PHAsset> // includes hidden assets by default
         
         open class func fetchKeyAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>?
         
         open class func fetchAssets(withBurstIdentifier burstIdentifier: String, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         
         // Fetches PHAssetSourceTypeUserLibrary assets by default (use includeAssetSourceTypes option to override)
         open class func fetchAssets(with options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         open class func fetchAssets(with mediaType: PHAssetMediaType, options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         
         
         // assetURLs are URLs retrieved from ALAsset's ALAssetPropertyAssetURL
         @available(iOS, introduced: 8.0, deprecated: 11.0, message: "Will be removed in a future release")
         open class func fetchAssets(withALAssetURLs assetURLs: [URL], options: PHFetchOptions?) -> PHFetchResult<PHAsset>
         */
        allOptions.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: true)]
        let allResults = PHAsset.fetchAssets(with: allOptions)
        
        return allResults
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        topView.addSubview(collectionView)
        downView.addSubview(collectionView2)
    }
    
    deinit {
        
    }
}

extension SelectViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return photosArray.count
        }else {
            return self.collectionView.indexPathsForSelectedItems?.count ?? 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SelectCollectionViewCellID", for: indexPath) as! SelectCollectionViewCell
            cell.asset = photosArray[indexPath.row]
            if collectionView.indexPathsForSelectedItems?.contains(indexPath) ?? false {
                cell.selectState = true
            } else {
                cell.selectState = false
            }
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SelectCollectionViewCellID2", for: indexPath) as! SelectCollectionViewCell
            cell.stateButton.imageView?.image = UIImage.init(named: "xianshi_quxiao")
            let tmpIndexPath = self.collectionView.indexPathsForSelectedItems![indexPath.row]
            cell.asset = photosArray[tmpIndexPath.row]
            
            return cell
        }
    }
}

extension SelectViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == self.collectionView {
            guard let cell: SelectCollectionViewCell = collectionView.cellForItem(at: indexPath) as? SelectCollectionViewCell else {return}
            cell.selectState = true
            self.collectionView2.reloadData()
        } else {
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        if collectionView == self.collectionView {
            guard let cell: SelectCollectionViewCell = collectionView.cellForItem(at: indexPath) as? SelectCollectionViewCell else {return}
            cell.selectState = false
            self.collectionView2.reloadData()
        }
    }
}

extension SelectViewController: photosCancelDelegate {
    func photosCancelAction(_ asset: PHAsset?) {
        
    }
}
